/**
 * 
 */
package com.csair.youth.web.action;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;

import com.csair.youth.constant.Constant;
import com.csair.youth.constant.ResourceConstant;
import com.csair.youth.database.Resource;
import com.csair.youth.database.SysConfig;
import com.csair.youth.service.impl.CategoryServiceImpl;
import com.csair.youth.service.impl.ResourceServiceImpl;
import com.csair.youth.service.impl.SysConfigServiceImpl;

/**
 * @author mickey
 *
 */
public class ResourceAuditAction extends _BaseAction {
	private Resource item;
	private ResourceServiceImpl service;
	private CategoryServiceImpl categoryService;
	private SysConfigServiceImpl sysConfigService;
	private String p;
	
	public Resource getItem() {
		return item;
	}

	public void setItem(Resource item) {
		this.item = item;
	}

	public ResourceServiceImpl getService() {
		return service;
	}

	public void setService(ResourceServiceImpl service) {
		this.service = service;
	}

	public CategoryServiceImpl getCategoryService() {
		return categoryService;
	}

	public void setCategoryService(CategoryServiceImpl categoryService) {
		this.categoryService = categoryService;
	}

	public SysConfigServiceImpl getSysConfigService() {
		return sysConfigService;
	}

	public void setSysConfigService(SysConfigServiceImpl sysConfigService) {
		this.sysConfigService = sysConfigService;
	}

	public String getP() {
		return p;
	}

	public void setP(String p) {
		this.p = p;
	}

	public String goAuditHome(){
		return SUCCESS;
	}
	
	public String execute(){
		String id = p;
		if(StringUtils.isEmpty(id)){
			this.setMessage("参数错误.");
			return INPUT;
		}
		item = service.getResourceWithUser(id);
		if(item == null) {
			this.setMessage("根据传入参数无法找到资源.");
			return INPUT;
		}
		return SUCCESS;
	}
	
	public String doAudit(){
		if(item == null || StringUtils.isEmpty(item.getId())){
			this.setMessage("资源对象为空");
		}
		if(!validInput(item)){
			return execute();
		}
		SysConfig httpConfig = sysConfigService.getSysConfigByKey(Constant.SERVER_IP_PORT_KEY);
		SysConfig ftpConfig = sysConfigService.getSysConfigByKey(Constant.SERVER_FTP_KEY);
		Resource res = service.getResource(item.getId());
		res.setAuditResult(item.getAuditResult());
		res.setAuditRemark(item.getAuditRemark());
		res.setAuditUserId((String)this.getSessionAttribute(Constant.USER_ID_SESSION_KEY));
		res.setAuditIp(this.getServletRequest().getRemoteAddr());
		res.setAuditTime(new Date());
		res.setLastModifyTime(new Date());
		
		//如果是第一次审核且通过了，需要从tmp目录转移
		String path = res.getAbsolutePath();
//		if(path.startsWith(Constant.UPLOAD_TMP_PATH) && Constant.RESOURCE_AUDIT_PASS.equals(res.getAuditResult())){
		if(path.startsWith(ResourceConstant.getInstance().getUploadTmpPath()) && item.getAuditResult().equals(Constant.RESOURCE_AUDIT_PASS)){
			//转移，以供下载(通过的先转移到目标目录，到时候可以选择删掉)
//			Calendar cal = Calendar.getInstance();
//			int year = cal.get(Calendar.YEAR);
//			int month = cal.get(Calendar.MONTH)+1;
//			String destPath = ResourceConstant.getInstance().getUploadStorePath() + File.separator + year + File.separator + month;
			//MODIFY ON 20101229 路径改为与ftp分类目录同步!!!
			String categoryPath = categoryService.getCategoryAbsolutePath(res.getCategoryId(), null);
			String categoryPathFtp = categoryService.getCategoryAbsolutePath(res.getCategoryId(), "/");
			String destPath = ResourceConstant.getInstance().getUploadStorePath() + categoryPath;
			File dir = new File(destPath);
			if(!dir.exists()){
				boolean suc = dir.mkdirs();
				if(!suc){
					this.setMessage("资源审核过程中发生错误[0]");	//mkdir失败
					return execute();
				}
			}
//			String ext = ".tmp";
//			if(path.lastIndexOf(".")>0){
//				ext = path.substring(path.lastIndexOf("."));
//			}
			String destFileName = System.currentTimeMillis()+"_"+res.getFileName();
			String destFilePath = destPath + File.separator + destFileName;
			try {
				File src = new File(path);
				File dest = new File(destFilePath);
				FileUtils.copyFile(src, dest);
				src.delete();
				res.setAbsolutePath(destFilePath);
				res.setHttpDownAddress(httpConfig.getConfigValue()+"/ResourceDownload.do?p="+p);
				res.setFtpDownAddress(ftpConfig.getConfigValue()+categoryPathFtp+"/"+destFileName);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.setMessage("资源审核过程中发生错误[1]");	//copy失败
			}
		}else if(path.startsWith(ResourceConstant.getInstance().getUploadStorePath()) && item.getAuditResult().equals(Constant.RESOURCE_AUDIT_FAIL)){
			//如果是后来再选择不通过的，则回到tmp目录
			String destPath = ResourceConstant.getInstance().getUploadTmpPath();
			File dir = new File(destPath);
			if(!dir.exists()){
				boolean suc = dir.mkdirs();
				if(!suc){
					this.setMessage("资源审核过程中发生错误[2]");	//mkdir失败
					return execute();
				}
			}
//			String ext = ".tmp";
//			if(path.lastIndexOf(".")>0){
//				ext = path.substring(path.lastIndexOf("."));
//			}
			String destFilePath = destPath + File.separator + System.currentTimeMillis()+"_"+res.getFileName();
			try {
				File src = new File(path);
				File dest = new File(destFilePath);
				FileUtils.copyFile(src, dest);
				src.delete();
				res.setAbsolutePath(destFilePath);
				res.setHttpDownAddress("");
				res.setFtpDownAddress("");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				this.setMessage("资源审核过程中发生错误[3]");	//copy失败
			}
		}
		service.saveResource(res);
		this.setMessage("资源审核完成.本次审核结果为:"+(StringUtils.equals(item.getAuditResult(), Constant.RESOURCE_AUDIT_PASS)?"通过":"不通过"));
		return execute();
	}
	
	private boolean validInput(Resource item){
		if(item == null) return false;
		boolean allValid = true;
		StringBuffer msgBf = new StringBuffer();
		String desc = item.getAuditRemark();
		if(!StringUtils.isEmpty(desc) && StringUtils.length(desc)> 120){
			msgBf.append("备注必须在120个字符内<br/>");
			allValid = false;
		}
		String auditResult = item.getAuditResult();
		if(StringUtils.isEmpty(auditResult) || (!Constant.RESOURCE_AUDIT_PASS.equals(auditResult) && !Constant.RESOURCE_AUDIT_FAIL.equals(auditResult))){
			msgBf.append("必须选择审核结果<br/>");
			allValid = false;
		}
		this.setMessage(msgBf.toString());
		return allValid;
	}
}
